<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="Cache-control" content="no-cache" />
    <title>表单发布</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="Expires" content="-1">
    <meta http-equiv="Pragma" content="no-cache">
    <meta name="description" content="">
    <meta name="keywords" content="" />
    <link rel="stylesheet" type="text/css" href="static/css/aui.2.0.css">
    <script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #3c445e;">
        <a onclick="history.back()" class="aui-pull-left">
            <i class="aui-iconfont aui-icon-left"></i>
        </a>
        <div class="aui-title">回复</div>
    </header>
    <form action="">
        <div>
            <div class="publish-article-title">
                <div class="title-tips">标题</div>
                <input type="text" id="title" placeholder="文章标题">
            </div>
            <div class="aui-padded f12 txt-muted">
                <span>引用 x楼 白老师</span>
                <div class="quote-content">照片说明：攀登四姑娘山三峰，在二峰和三峰之间的垭口,太阳就慢慢露了出来，雪山上的日出，真</div>
            </div>
            <div class="publish-article-content">
                <div class="article-content" id="content"></div>
            </div>
        </div>
        <div class="aui-padded aui-border-t bg-f">
            <div class="aui-row-padded aui-row" id="ossfile"></div>
            <div id="console"></div>
        </div>
        <!-- <div class="aui-border-tb bg-f" id="container">
            <img class="aui-padded" src="static/images/icon_smile.png" style="width: 2.5rem;vertical-align: top;" onclick="toOpenFace()">
            <img class="aui-padded" id="selectfiles" src="static/images/icon_img.png" style="width: 2.5rem;vertical-align: top;">
            
            <input type="file" id="file_list">

            <div class="aui-pull-right">
                <button type="submit" class="aui-btn aui-btn-info aui-margin-t-10 aui-margin-r-15">发布</button>
            </div>
        </div> -->
    

        <div id="wrapper">
            <div id="container">
                <div id="uploader">
                    <div class="queueList">
                        <div id="dndArea" class="placeholder">
                            <div id="filePicker"></div>
                            <p>您可以尝试文件拖拽，使用QQ截屏工具，然后激活窗口后粘贴，或者点击添加图片按钮</p>
                        </div>
                    </div>
                    <div class="statusBar" style="display: none;">
                        <div class="progress">
                            <span class="text">0%</span> <span class="percentage"></span>
                        </div>
                        <div class="info"></div>
                        <div class="btns">
                            <div id="filePicker2"></div>
                            <div class="uploadBtn">开始上传</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </form>
</body>
<script src="static/js/loader.js"></script>
<script type="text/javascript">
window.serverUrl = './get.php'; //获取签名接口
window.filename_pre = '34_'; //上传返回的文件名前缀，届时请替换成USER_ID

// .setGlobalDefaults({BasePath:'/123/'})
$LAB
    .css('static/css/arteditor.css')
    // .script('static/js/plupload-2.1.2/js/plupload.full.min.js','static/js/upload.js')
    .css('https://cdn.staticfile.org/webuploader/0.1.5/webuploader.css')
    .script('https://cdn.staticfile.org/webuploader/0.1.5/webuploader.js').wait(function() {

        var objdata = {
            upfile_endpoint:'http://bmbbs.oss-cn-hangzhou.aliyuncs.com',//上传地址
            upfile_nametype:'random_name',//local_name random_name  上传文件的文件名类型
            upfile_defaltdir:'upload/CCCC'//上传路径 多层  格式  upload/floder1/floder2
        };
        // 当domReady的时候开始初始化
        $(function() {
            $.ajax({
                type : "post",
                url : "./get.php",
                timeout : 10000,
                data : {
                    "dir" : objdata.upfile_defaltdir
                },
                success : function(str) {
                    if (str) {
                        try {
                            var re = JSON.parse(str);
                            objdata.osssignature = {
                                'key' : re.dir,
                                'policy': re.policy,
                                'OSSAccessKeyId': re.accessid, 
                                'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                                'signature': re.signature
                            };
                        } catch (e) {
                            alert("系统错误");
                        }
                        
                    } else {
                        alert("结果为空");
                    }
                },
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("ajax error");
                },
                complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
                    if(status == 'timeout'){
                        alert('请求超时，请稍后再试！');
                    }
                },
                async : false
            });
            
            var $wrap = $('#uploader'),
            // 图片容器
            $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

            // 状态栏，包括进度和控制按钮
            $statusBar = $wrap.find('.statusBar'),

            // 文件总体选择信息。
            $info = $statusBar.find('.info'),

            // 上传按钮
            $upload = $wrap.find('.uploadBtn'),

            // 没选择文件之前的内容。
            $placeHolder = $wrap.find('.placeholder'),

            $progress = $statusBar.find('.progress').hide(),

            // 添加的文件数量
            fileCount = 0,

            // 添加的文件总大小
            fileSize = 0,

            acceptExtensions = [ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".xls", ".xlsx" ].join('').replace(/\./g, ',').replace(/^[,]/, ''),

            // 优化retina, 在retina下这个值是2
            ratio = window.devicePixelRatio || 1,

            // 缩略图大小
            thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio,

            // 可能有pedding, ready, uploading, confirm, done.
            state = 'pedding',

            // 所有文件的进度信息，key为file id
            percentages = {},
            // 判断浏览器是否支持图片的base64
            isSupportBase64 = (function() {
                var data = new Image();
                var support = true;
                data.onload = data.onerror = function() {
                    if (this.width != 1 || this.height != 1) {
                        support = false;
                    }
                }
                data.src = "";
                return support;
            })(),

            supportTransition = (function() {
                var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
                s = null;
                return r;
            })(), _this = this,
            // WebUploader实例
            uploader;
            _this.imageList = [];
           if (!WebUploader.Uploader.support()) {
                alert('Web Uploader 不支持您的浏览器！');
                return;
            }
            // 实例化
            uploader = WebUploader.create({
                pick : {
                    id : '#filePicker',
                    label : '点击选择图片'
                },
                /*accept : {
                    title : 'Images',
                    extensions : acceptExtensions,
                    // mimeTypes: 'filed/*' //wuzhifeng 修改上传文件类型 图片的话 是
                    // image
                    mimeTypes : 'image/*'
                },*/
                formData : {
                    uid : 123
                },
                // dnd : '#dndArea',    //指定Drag And Drop拖拽的容器，如果不指定，则不启动
                // paste : '#uploader', //添加截屏的图片
                swf : '/tbpt/plugin/ueditor/third-party/webuploader/Uploader.swf',
                chunked : false,
                chunkSize : 512 * 1024,
                server : objdata.upfile_endpoint,///tbpt/plugin/ueditor/jsp/controller.jsp?action=uploadimage  
                //http://oss.aliyuncs.com/ http://tbptfile.oss-cn-beijing.aliyuncs.com/
                // runtimeOrder: 'flash',
                // server:
                // 'http://liaoxuezhi.fe.baidu.com/webupload/fileupload.php',
                // server: 'http://www.2betop.net/fileupload.php',
                //

                // accept: {
                // title: 'Images',
                // extensions: 'gif,jpg,jpeg,bmp,png',
                // mimeTypes: 'image/*'
                // },

                // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                disableGlobalDnd : true,
                auto : false,// {Boolean} [可选] [默认值：false] 设置为 true
                // 后，不需要手动调用上传，有文件选择即开始上传。
                fileNumLimit : 300,// 验证文件总数量, 超出则不允许加入队列。
                fileSizeLimit : 200 * 1024 * 1024, // 200 M
                fileSingleSizeLimit :110 * 1024 * 1024 // 50 M
            });

            // 拖拽时不接受 js, txt 文件。
            uploader.on('dndAccept', function(items) {
                var denied = false, len = items.length, i = 0,
                // 修改js类型
                unAllowed = 'text/plain;application/javascript ';

                for (; i < len; i++) {
                    // 如果在列表里面
                    if (~unAllowed.indexOf(items[i].type)) {
                        denied = true;
                        break;
                    }
                }

                return !denied;
            });
            // 添加“添加文件”的按钮，
            uploader.addButton({
                id : '#filePicker2',
                label : '继续添加'
            });

            uploader.on('ready', function() {
                window.uploader = uploader;
            });

            // 当有文件添加进来时执行，负责view的创建
            function addFile(file) {
                var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'),

                $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li), $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'), $info = $('<p class="error"></p>'),

                showError = function(code) {
                    switch (code) {
                    case 'exceed_size':
                        text = '文件大小超出';
                        break;

                    case 'interrupt':
                        text = '上传暂停';
                        break;

                    default:
                        text = '上传失败，请重试';
                        break;
                    }

                    $info.text(text).appendTo($li);
                };

                if (file.getStatus() === 'invalid') {
                    showError(file.statusText);
                } else {
                    // @todo lazyload
                    $wrap.text('预览中');
                    uploader.makeThumb(file, function(error, src) {
                        var img;

                        if (error) {
                            $wrap.text('不能预览');
                            return;
                        }

                        if (isSupportBase64) {
                            img = $('<img src="' + src + '">');
                            $wrap.empty().append(img);
                        }
                    }, thumbnailWidth, thumbnailHeight);

                    percentages[file.id] = [ file.size, 0 ];
                    file.rotation = 0;
                }
                uploader.on('uploadBeforeSend', function (obj, data, headers) {
                    //TODO   如果同一个页面上传多次  需要处理签名逻辑   不用每次都签名
                    debugger
                    //赋值参数
                    data = $.extend(data,objdata.osssignature);
                    //设置文件路径
                    data.key = data.key + "/" + calculate_object_name(data.name,objdata.upfile_nametype);
                    obj.filepath = data.key;
                    file.path = data.key;
                    headers['Access-Control-Allow-Origin'] = "*";
                });
                //得到文件名 type local_name random_name
                function calculate_object_name(filename,type)
                {
                    if (type && type == 'local_name') {
                        return "${filename}";
                    } else {//随机生成文件名
                        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
                    　　var maxPos = chars.length;
                    　　var random_string = '';
                    　　for (i = 0; i < 10; i++) {
                        　　random_string += chars.charAt(Math.floor(Math.random() * maxPos));
                        }
                        var pos = filename.lastIndexOf('.')
                        var suffix = ''
                        if (pos != -1) {
                            suffix = filename.substring(pos);
                        }
                        return random_string + new Date().getTime() + suffix;
                    }
                }
                
                file.on('statuschange', function(cur, prev) {
                    if (prev === 'progress') {
                        $prgress.hide().width(0);
                    } else if (prev === 'queued') {
                        $li.off('mouseenter mouseleave');
                        $btns.remove();
                    }
                    // 成功
                    if (cur === 'error' || cur === 'invalid') {
                        console.log(file.statusText);
                        showError(file.statusText);
                        percentages[file.id][1] = 1;
                    } else if (cur === 'interrupt') {
                        showError('interrupt');
                    } else if (cur === 'queued') {
                        percentages[file.id][1] = 0;
                    } else if (cur === 'progress') {
                        $info.remove();
                        $prgress.css('display', 'block');
                    } else if (cur === 'complete') {
                        //$li.append('<span class="success"></span>');
                    }

                    $li.removeClass('state-' + prev).addClass('state-' + cur);
                });
                uploader.on('uploadAccept', function (file, response) {
                    var hasError = (response['error'] !== undefined);
                    if (hasError) {
                        // 通过return false来告诉组件，此文件上传有错。
                        return false;
                    };
                });
                //上传完成 服务器响应 不代表上传成功
                uploader.on('uploadSuccess', function(file, ret) {
                    debugger
                    var $file = $('#' + file.id);
                    if (!ret._raw) {
                        _this.imageList.push({
                            succ:true
                        });
                        $file.append('<span class="success"></span>');
                        //图片
                        if(file.type == 'image/jpeg'){
                            $('body').append('原图:<a href="'+ objdata.upfile_endpoint + "/" +file.path +'" target="_blank">'+ objdata.upfile_endpoint + "/" +file.path +'<a/>');
                            $('body').append('<img src="'+ objdata.upfile_endpoint + "/" +file.path +'?x-oss-process=image/resize,m_lfit,h_100,w_100" />');
                            $('body').append('<img src="'+ objdata.upfile_endpoint + "/" +file.path +'?x-oss-process=image/resize,m_fill,h_100,w_100" />');
                        }
                    } else {
                        showError(file.statusText);
                        $file.find('.error').text("失败").show();
                        console.log("上传失败");
                        $('body').append("上传失败");
                    }
                });
                $li.on('mouseenter', function() {
                    $btns.stop().animate({
                        height : 30
                    });
                });

                $li.on('mouseleave', function() {
                    $btns.stop().animate({
                        height : 0
                    });
                });

                $btns.on('click', 'span', function() {
                    var index = $(this).index(), deg;

                    switch (index) {
                    case 0:
                        uploader.removeFile(file);
                        return;

                    case 1:
                        file.rotation += 90;
                        break;

                    case 2:
                        file.rotation -= 90;
                        break;
                    }

                    if (supportTransition) {
                        deg = 'rotate(' + file.rotation + 'deg)';
                        $wrap.css({
                            '-webkit-transform' : deg,
                            '-mos-transform' : deg,
                            '-o-transform' : deg,
                            'transform' : deg
                        });
                    } else {
                        $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                    }

                });

                $li.appendTo($queue);
            }

            // 负责view的销毁
            function removeFile(file) {
                var $li = $('#' + file.id);

                delete percentages[file.id];
                updateTotalProgress();
                $li.off().find('.file-panel').off().end().remove();
            }

            function updateTotalProgress() {
                var loaded = 0, total = 0, spans = $progress.children(), percent;

                $.each(percentages, function(k, v) {
                    total += v[0];
                    loaded += v[0] * v[1];
                });

                percent = total ? loaded / total : 0;

                spans.eq(0).text(Math.round(percent * 100) + '%');
                spans.eq(1).css('width', Math.round(percent * 100) + '%');
                updateStatus();
            }

            function updateStatus() {
                var text = '', stats;

                if (state === 'ready') {
                    text = '选中' + fileCount + '张图片，共' + WebUploader.formatSize(fileSize) + '。';
                } else if (state === 'confirm') {
                    stats = uploader.getStats();
                    if (stats.uploadFailNum) {
                        text = '已成功上传' + stats.successNum + '张照片，' + stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                    }

                } else {
                    stats = uploader.getStats();
                    text = '共' + fileCount + '张（' + WebUploader.formatSize(fileSize) + '），已上传' + stats.successNum + '张';

                    if (stats.uploadFailNum) {
                        text += '，失败' + stats.uploadFailNum + '张';
                    }
                }

                $info.html(text);
            }

            function setState(val) {
                var file, stats;

                if (val === state) {
                    return;
                }

                $upload.removeClass('state-' + state);
                $upload.addClass('state-' + val);
                state = val;

                switch (state) {
                case 'pedding':
                    $placeHolder.removeClass('element-invisible');
                    $queue.hide();
                    $statusBar.addClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'ready':
                    $placeHolder.addClass('element-invisible');
                    $('#filePicker2').removeClass('element-invisible');
                    $queue.show();
                    $statusBar.removeClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'uploading':
                    $('#filePicker2').addClass('element-invisible');
                    $progress.show();
                    $upload.text('暂停上传');
                    break;

                case 'paused':
                    $progress.show();
                    $upload.text('继续上传');
                    break;

                case 'confirm':
                    $progress.hide();
                    $upload.text('开始上传').addClass('disabled');

                    stats = uploader.getStats();
                    if (stats.successNum && !stats.uploadFailNum) {
                        setState('finish');
                        return;
                    }
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    if (stats.successNum) {

                        // WuZhiFeng

                    } else {
                        // 没有成功的图片，重设
                        state = 'done';
                        location.reload();
                    }
                    break;
                }

                updateStatus();
            }

            uploader.onUploadProgress = function(file, percentage) {
                var $li = $('#' + file.id), $percent = $li.find('.progress span');

                $percent.css('width', percentage * 100 + '%');
                percentages[file.id][1] = percentage;
                updateTotalProgress();
            };

            uploader.onFileQueued = function(file) {
                fileCount++;
                fileSize += file.size;

                if (fileCount === 1) {
                    $placeHolder.addClass('element-invisible');
                    $statusBar.show();
                }

                addFile(file);
                setState('ready');
                updateTotalProgress();
            };

            uploader.onFileDequeued = function(file) {
                fileCount--;
                fileSize -= file.size;

                if (!fileCount) {
                    setState('pedding');
                }

                removeFile(file);
                updateTotalProgress();

            };

            uploader.on('all', function(type) {
                var stats;
                switch (type) {
                case 'uploadFinished':
                    setState('confirm');
                    break;

                case 'startUpload':
                    setState('uploading');
                    break;

                case 'stopUpload':
                    setState('paused');
                    break;

                }
            });

            uploader.onError = function(code) {
                if (code == 'Q_TYPE_DENIED') {
                    alert("不支持该文件类型，请选择图片类型文件");// WuZhiFeng 20140822
                }
                if (code == 'Q_EXCEED_NUM_LIMIT') {
                    alert("只能上传单张图片");// WuZhiFeng 20140822
                }
                // alert( 'Eroor: ' + code );
            };

            $upload.on('click', function() {
                if ($(this).hasClass('disabled')) {
                    return false;
                }

                if (state === 'ready') {
                    uploader.upload();
                } else if (state === 'paused') {
                    uploader.upload();
                } else if (state === 'uploading') {
                    uploader.stop();
                }
            });

            $info.on('click', '.retry', function() {
                uploader.retry();
            });

            $info.on('click', '.ignore', function() {
                alert('todo');
            });

            $upload.addClass('state-' + state);
            updateTotalProgress();
        });
        
    })
    .script('static/js/arteditor.js').wait(function() {
        var arteditor = $('#content').artEditor({
            imgTar: '#imageUpload',
            limitSize: 5, // 兆
            showServer: false,
            data: {},
            uploadField: 'image',
            breaks: false,
            placeholader: '请输入回复内容',
            validHtml: ["<br/>"],
            formInputId: 'target',
        });

        toOpenFace = function() {
            var face = openFace(function() {
                var img = ' <img src="' + this.src + '" style="max-width:100%;" /> '
                arteditor.insertImage(img);
                face.closed();
            })
        };


        $('#ossfile').on('click', 'img.eui-wmax', function() {
            var img = '<p> <img src="' + this.src + '" style="max-width:100%;" /> </p>'
            arteditor.insertImage(img);
        })

        $('#submit').on('click', function() {
            $('#content').val($('.article-content').html())
            $('#reply_add').submit();
        })
    })
</script>

</html>